package xwj.example.demo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class UsingApiMetric {
    Map<String, ApiMetric> metrics = Collections.synchronizedMap(new HashMap<>());

    public Map<String, ApiMetric> getMetrics() {
        return metrics;
    }

    @Around("@within(org.springframework.web.bind.annotation.RestController)")
    public Object usingApiMetric(ProceedingJoinPoint joinPoint)throws Throwable{
        String methodName=joinPoint.getSignature().toString();
        ApiMetric metric;
        if(metrics.containsKey(methodName)){
            metric=metrics.get(methodName);
        }
        else{
            metric=new ApiMetric();
            metrics.put(methodName, metric);
        }
        try {
            long t1 = Calendar.getInstance().getTimeInMillis();
            Object result= joinPoint.proceed();
            long t2 = Calendar.getInstance().getTimeInMillis();
            metric.addExecution();
            metric.addTime((int)(t2-t1));
            return result;
        }
        catch(Throwable e){
            metric.addException(e);
            throw e;
        }
    }
}
